package org.lemon.cla.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * AI 对话控制器
 * 提供基于 Spring AI 的聊天和问候功能。
 */
@Slf4j
@RestController
@RequestMapping("/ai")
@Tag(name = "AI对话接口", description = "提供基于 AI 的聊天和问候功能")
public class ChatController {

    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(new InMemoryChatMemory())
                )
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7)
                                .build()
                )
                .build();
    }

    /**
     * 进行一次简单的 AI 聊天。
     *
     * @param query 用户的输入问题。
     * @return AI 的回答。
     */
    @GetMapping("/simple/chat")
    @Operation(summary = "进行一次简单的 AI 聊天", description = "用户输入问题，AI 返回相应的答案。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取 AI 回复",
                    content = @io.swagger.v3.oas.annotations.media.Content(mediaType = "text/plain",
                            examples = @io.swagger.v3.oas.annotations.media.ExampleObject(value = "我是通义千问，一个由阿里巴巴训练的大型语言模型。"))),
            @ApiResponse(responseCode = "400", description = "请求参数缺失或格式不正确"),
            @ApiResponse(responseCode = "500", description = "AI 服务内部错误")
    })
    public String simpleChat(
            @Parameter(description = "用户要问 AI 的问题", required = true, example = "你好，你是谁？")
            @RequestParam String query) {
        String text = chatClient.prompt(query).call().content();
        return text;
    }
}